<template>
  <div class="widthAll">
    <div style="text-align: right;">
      <el-button size="small" style="border: none; margin-right: 45px;" @click="down"><span
          class="iconfont icon-social-buysellads"
          style="font-size: 20px;"></span>
      </el-button>
    </div>
    <div id="main" style="height: 370px;width: 100%;"></div>
  </div>
</template>

<script>

import {EleResize} from "@/assets/js/resize";
import {getCollapse} from "@/api/session";
import html2canvas from "html2canvas"
import {getProductCount, getProducts} from "@/api/product";
import {getSellCount, getSells} from "@/api/sell";
import {getBuyCount, getBuys} from "@/api/buy";

export default {
  name: 'index',
  data() {
    return {
      sc: 0,
      pc: 0,
      bc: 0,
      myChart: null,
      div: null,
      products: ['小米手环', '电冰箱', '充电宝'],
      ids: [],
      buys: [10, 8, 9],
      sells: [7, 1, 3],
      sellMap: new Map(), // product id->num
      buyMap: new Map()
    }
  },
  mounted() {
    const _this = this;
    getSellCount().then(rs => {
      _this.sc = rs.message;
      getBuyCount().then(rs => {
        _this.bc = rs.message;
        getProductCount().then(rs => {
          _this.pc = rs.message;
          _this.div = document.getElementById('main');
          _this.preHandle();
          _this.fetchData();
        });
      });
    });
  },
  // 此时,页面上的元素,已经被渲染完毕了
  methods: {
    fetchData() {
      const _this = this;
      getProducts({pageSize: _this.pc, pageNo: 1}).then(rs => {
        _this.products = [];
        _this.ids = [];
        console.log(rs)
        rs.message.records.forEach(item => {
          _this.products.push(item.pname);
          _this.ids.push(item.pid);
          _this.sellMap.set(item.pid, 0);
          _this.buyMap.set(item.pid, 0);
          _this.sellMap = new Map(_this.sellMap);
          _this.buyMap = new Map(_this.buyMap);
        });

        console.log(_this.products)
        console.log(_this.ids)

        getSells({pageNo: 1, pageSize: this.sc}).then(rs => {
          rs.message.records.forEach(item => {
            _this.sellMap.set(item.pid, _this.sellMap.get(item.pid) + item.sellNumber);
            _this.sellMap = new Map(_this.sellMap);
          });

          getBuys({pageNo: 1, pageSize: this.bc}).then(rs => {
            rs.message.records.forEach(item => {
              _this.buyMap.set(item.pid, _this.buyMap.get(item.pid) + item.buyNumber);
              _this.buyMap = new Map(_this.buyMap);
            });
            _this.merge();
          })
        })
      })

    },
    merge() {
      const _this = this;
      _this.buys = [];
      _this.sells = [];
      _this.ids.forEach(item => {
        _this.buys.push(_this.buyMap.get(item));
        _this.sells.push(_this.sellMap.get(item));
      })
      _this.refresh(); //绘制图表
      _this.afterHandle();
    },
    preHandle() {
      if (getCollapse()) /*不这么设置的话，echarts宽度有问题,93相当于去除侧边栏以及周边空白的部分*/
        this.div.style.width = document.body.clientWidth - 93 + 'px';
    },
    afterHandle() {
      const _this = this;
      let listener = function () {
        _this.myChart.resize();
      }
      EleResize.on(_this.div, listener)
      _this.div.style.width = '100%';
    },
    down() {
      /*下载为png图片*/
      html2canvas(document.getElementById("main")).then(function (canvas) {
        var img = canvas
            .toDataURL("image/png")
            .replace("image/png", "image/octet-stream");
        // 创建a标签，实现下载
        var creatIMg = document.createElement("a");
        creatIMg.download = "erp.png"; // 设置下载的文件名，
        creatIMg.href = img; // 下载url
        document.body.appendChild(creatIMg);
        creatIMg.click();
        creatIMg.remove(); // 下载之后把创建的元素删除
      });
    },
    refresh() {
      const _this = this;
      let echarts = require('echarts');
      _this.myChart = echarts.init(document.getElementById('main'));
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: ['采购', '销售']
        },
        title: {
          text: '后台报表',
          subtext: '各分类借阅数以及书籍数'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          data: _this.products,
          axisLabel: {
            interval: 0,
            inside: false,
            textStyle: {
              color: '#6F7691',
              fontSize: 15,
              itemSize: ''
            }
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
          },
          axisLine: {
            show: true
          },
          z: 10
        },
        yAxis: {
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            textStyle: {
              color: '#999'
            }
          }
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            type: 'bar',
            name: '采购',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [ /*渐变式柱形条*/
                    {offset: 0, color: '#83bff6'},
                    {offset: 0.5, color: '#188df0'},
                    {offset: 1, color: '#188df0'}
                  ]
              )
            },
            data: _this.buys,
            emphasis: {
              focus: 'series'
            },
          },
          {
            name: '销售',
            type: 'bar',
            data: _this.sells,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(
                  0, 0, 0, 1,
                  [
                    {offset: 0, color: '#f88596'},
                    {offset: 0.5, color: '#F66A81'},
                    {offset: 1, color: '#F4516c'}
                  ]
              )
            },
            emphasis: {
              focus: 'series'
            },
          },

        ],
        animationEasing: 'cubicOut', //elasticOut另一种效果
        animationDuration: function (idx) {
          // 越往后的数据时长越大
          return idx * 100;
        },
        animationDelay: function (idx) {
          // 越往后的数据延迟越大
          return idx * 100;
        },
        animation: true,
      };

      // Enable data zoom when user click bar.
      const zoomSize = 10;
      _this.myChart.on('click', function (params) {
        _this.myChart.dispatchAction({
          type: 'dataZoom',
          startValue: _this.products[Math.max(params.dataIndex - zoomSize / 2, 0)],
          endValue: _this.products[Math.min(params.dataIndex + zoomSize / 2, _this.buys.length - 1)]
        });
      });
      _this.myChart.clear();
      _this.myChart.setOption(option, true)
    },

  }
}
</script>
